package main

import (
	"context"
	mygin "e-commerce/services/order-service/api/gin"
	mygrpc "e-commerce/services/order-service/api/grpc"
	"e-commerce/services/order-service/otel"
	"log"
	"net"

	orderpb "e-commerce/services/order-service/api/pb"
	mq "e-commerce/services/order-service/internal/mq"

	otelgin "go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
	otelgrpc "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"

	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
)

func main() {
	shutdown, err := otel.InitTracer("order-service", "services/order-service/config/devconfig.yaml")
	if err != nil {
		log.Fatalf("Failed to initialize tracer: %v", err)
	}
	defer func() {
		if err := shutdown(context.Background()); err != nil {
			log.Printf("Failed to shutdown tracer: %v", err)
		}
	}()
	orderHandler, err := mygin.NewOrderHandler("services/order-service/config/devconfig.yaml")
	// 添加中间件
	r := gin.Default()
	r.Use(
		otelgin.Middleware("order-service"),
		orderHandler.Middleware(),
	)
	if err != nil {
		log.Fatalf("Failed to create order handler: %v", err)
	}
	r.POST("/orders", orderHandler.CreateOrder)
	r.GET("/orders/:id", orderHandler.GetOrder)
	r.POST("/orders/:id", orderHandler.CancelOrder)
	r.POST("/orders/:id/paid", orderHandler.MarkOrderPaid)
	go r.Run(":8083")

	lis, err := net.Listen("tcp", ":50053")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	} else {
		log.Printf("server listening at %v", lis.Addr())
	}
	orderService, err := mygrpc.NewOrderService("services/order-service/config/devconfig.yaml")
	if err != nil {
		log.Fatalf("Failed to create order service: %v", err)
	}

	otelHandler := otelgrpc.NewServerHandler()
	grpcServer := grpc.NewServer(
		grpc.ChainUnaryInterceptor(
			orderService.AuthMiddleware,
		),
		grpc.StatsHandler(otelHandler),
	)

	orderpb.RegisterOrderServiceServer(grpcServer, orderService)

	go grpcServer.Serve(lis)

	// 监听rabbitmq队列
	orderMQ := orderService.Service.Mq
	// 创建队列，绑定交换机
	err = mq.NewOrderQueue(orderMQ)
	if err != nil {
		log.Fatalf("创建队列失败: %v", err)
	}

	err = orderMQ.Consume("order.stock_reserved", orderService.Service.Repo)
	if err != nil {
		log.Fatalf("消费order.stock_reserved消息失败: %v", err)
	}
	err = orderMQ.Consume("order.stock_failed", orderService.Service.Repo)
	if err != nil {
		log.Fatalf("消费order.stock_failed消息失败: %v", err)
	}

	select {}
}
